Page({
  data: {
    isFocus: false, 
    descContent: '', 
    selectedImages: [], 
  },

  onLoad(options) {
    if (options.images) {
      const images = JSON.parse(options.images);
      this.setData({ selectedImages: images });
    }
  },

  gotoSelectImage() {
    wx.navigateTo({
      url: '/transmit/pages/transmithomework/transmithomework'
    });
  },

  focusInput() {
    this.setData({ isFocus: true });
  },

  onDescInput(e) {
    this.setData({ descContent: e.detail.value });
  },

  publishWork() {
    const { descContent, selectedImages } = this.data;
    
    // 表单验证
    if (!descContent.trim()) {
      wx.showToast({ title: "请填写描述", icon: "none" });
      return;
    }
    
    if (selectedImages.length === 0) {
      wx.showToast({ title: "请至少选择一张图片", icon: "none" });
      return;
    }

    // 显示加载提示
    wx.showLoading({ title: '正在发布...' });

    // 引入网络请求工具
    const { post } = require('../../../utils/request.js');
    
    // 准备发送的数据
    const workData = {
      content: descContent.trim(),
      coverImg: selectedImages[0] // 取第一张图片作为封面图
    };

    console.log("准备发送的作品数据:", workData);
    
    // 发送POST请求到服务器
    post('/collect/works/insert', workData)
      .then(res => {
        console.log("发布成功，服务器响应:", res);
        
        wx.hideLoading();
        wx.showToast({ 
          title: "发布成功", 
          icon: "success",
          duration: 2000
        });
        
        // 发布成功后重置表单
        setTimeout(() => {
          this.setData({
            descContent: "",
            selectedImages: []
          });
        }, 2000);
      })
      .catch(err => {
        console.error('发布失败:', err);
        
        wx.hideLoading();
        wx.showToast({ 
          title: "发布失败，请重试", 
          icon: "none",
          duration: 2000
        });
      });
  },

  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const newImages = [...this.data.selectedImages];
    newImages.splice(index, 1); 
    this.setData({ selectedImages: newImages });
  }
})